#!/bin/bash
root_dir="/usr/local/edata"
#----------------------------------------------------------------------
if [ ! -d "$root_dir" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING $root_dir undetected"
  mkdir -p $root_dir
  if [ $? -eq 0 ];then
    echo "$(date +"%Y-%m-%d %H:%M:%S") INFO creating $root_dir success"
  else
    echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR creating $root_dir fail"
    exit 1
  fi
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO $root_dir detected"
fi
#----------------------------------------------------------------------
jdk_ver=$(java -version 2>&1)
if [[ $jdk_ver == *"1.8.0_221"* ]];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO jdk 1.8.0_221 detected"
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR jdk (1.8.0_221 is required) is not found,install it first"
fi
#----------------------------------------------------------------------
zk_proc=$(jps | grep "QuorumPeerMain" 2>&1)
if [[ $zk_proc == *"QuorumPeerMain"* ]];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING zookeeper process detected"
  exit 0
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO zookeeper process undetected"
fi
#----------------------------------------------------------------------
if [ ! -d "$root_dir/zk" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO $root_dir/zk undetected"
  tar -xvf apache-zookeeper-3.7.1-bin.tar.gz
  mv apache-zookeeper-3.7.1-bin $root_dir/zk
  mkdir -p $root_dir/zk/data
  mkdir -p $root_dir/zk/logs
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING $root_dir/zk detected"
fi
#----------------------------------------------------------------------
env_file="zk.env"
if [ ! -f "$env_file" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") env file $env_file is not existed"
  exit 1
fi
while IFS='=' read -r key value
do
  echo "$(date +"%Y-%m-%d %H:%M:%S") setting $key=$value"
  echo "$key=$value" >> $root_dir/zk/conf/zoo.cfg
done < "$env_file"
id_file="$root_dir/zk/data/myid"
if [ ! -f "$id_file" ];then
  echo $1 >>  $id_file
fi
if [[ -z "$ZK_HOME" ]];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING ZK_HOME env is not set,setting..."
  echo "export ZK_HOME=$root_dir/zk" >> ~/.bashrc
  echo 'export PATH=$ZK_HOME/bin:$PATH' >> ~/.bashrc
  echo "export ZK_HOME=$root_dir/zk" >> /etc/profile
  echo 'export PATH=$ZK_HOME/bin:$PATH' >> /etc/profile
  source ~/.bashrc
  source /etc/profile
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO ZK_HOME is set"
fi
#-----------------------------------------------------------------------
zkServer.sh version
if [  $? -eq 0 ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO zookeeper setup success"
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO zookeeper setup error"
fi



